package io.renren.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import io.renren.modules.archive.entity.ArchiveInfoEntity;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExportUtils {

    /**
     * 数据导出
     * @param fileName 导出excel名称
     * @param objects 导出的数据
     * @param c 导出数据的实体class
     * @param response 响应
     * @throws Exception
     */
    public static void exportExcel(String fileName, List<?> objects, Map<String,String> headerName, Class<?> c, HttpServletResponse response) throws Exception {
        try {
            // 创建表头
            // 创建工作薄
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet();
            // 创建表头行
            Row rowHeader = sheet.createRow(0);
            if (c == null) {
                throw new RuntimeException("Class对象不能为空!");
            }
            Field[] declaredFields = c.getDeclaredFields();
            List<String> headerList = new ArrayList<>();
            if (declaredFields.length == 0) {
                return;
            }
            int n = 0;
            for (Map.Entry<String, String> entry : headerName.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                Cell cell = rowHeader.createCell(n, CellType.STRING);
                headerList.add(n, value);
                cell.setCellValue(key);
                n=n+1;
            }

            // 填充数据

            Object obj = c.newInstance();
            if (!CollectionUtils.isEmpty(objects)) {
                for (int o = 0; o < objects.size(); o++) {
                    Row rowData = sheet.createRow(o + 1);
                    for (int i = 0; i < headerList.size(); i++) {
                        Cell cell = rowData.createCell(i);
                        Field nameField = c.getDeclaredField(headerList.get(i));
                        nameField.setAccessible(true);
                        String type = nameField.getType().getName();

                        String value = String.valueOf(nameField.get(objects.get(o)));
                        if(value==null||value.equals("null")){
                            value="";
                        }
                        if(StringUtils.equals(type,"java.util.Date")){
                         value= bzstrToStr(value);
                        }
                        cell.setCellValue(value);
                    }
                }
            }
            response.setContentType("application/vnd.ms-excel");
            String resultFileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + resultFileName + ";" + "filename*=utf-8''" + resultFileName+".xlsx");
            workbook.write(response.getOutputStream());
            workbook.close();
            response.flushBuffer();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }




    /**
     * 导入
     * @param workbook 工作簿
     * @param c 实体类
     * @return 实体类集合
     */
    public static <T> R importExcel(Workbook workbook,Class<?> c,Map<String,String> headerName){
        List<T> dataList = new ArrayList<>();
        try {
            Sheet sheet = workbook.getSheetAt(0);
            int i = 0;
            T o = null;
            List<String> headList=new ArrayList<>();
            Row headRow = sheet.getRow(0);
            for(int n=0;n<headRow.getLastCellNum();n++){
                Cell cell = headRow.getCell(n);
                String value = String.valueOf(cell);
                headList.add(value);
            }

            for (Row row : sheet) {
                Row row1 = sheet.getRow(i + 1);
                if(row1 != null){
                    o = (T) c.newInstance();
                    Field[] declaredFields = c.getDeclaredFields();
                    for (int i1 = 0; i1 < headList.size(); i1++) {
                        String name =headerName.get(headList.get(i1));
                        Field declaredField1 = o.getClass().getDeclaredField(name);
                        declaredField1.setAccessible(true);

                        if(row1.getCell(i1)!= null){
                              row1.getCell(i1).setCellType(CellType.STRING);
                        }
                        Cell cell = row1.getCell(i1);
                        String type = declaredField1.getType().getName();
                        String value = String.valueOf(cell);
                        if(name.equals("nd")){
                            if(value.equals("")){
                                return R.error("年度不能为空");
                            }
                            String regex = "^\\d{4}$";

                            Pattern pattern = Pattern.compile(regex);
                            Matcher matcher = pattern.matcher(value);

                            if (!matcher.matches()) {
                                return R.error("年度必须为四位数字");
                            }
                        }else  if(name.equals("title")){
                            if(value.equals("")){
                                return R.error("提名不能为空");
                            }

                        }else  if(name.equals("author")){
                            if(value.equals("")){
                                return R.error("责任者不能为空");
                            }

                        }else  if(name.equals("rq")){
                            if(value.equals("")){
                                return R.error("日期不能为空");
                            }

                        }else  if(name.equals("wh")){
                            if(!value.equals("")){
                                String regex = "^[\u4e00-\u9fa5]{2}\\[\\d{4}\\]\\d+号$";
                                Pattern pattern = Pattern.compile(regex);
                                Matcher matcher = pattern.matcher(value);

                                if (!matcher.matches()) {
                                    return R.error("请按照规范书写问号，例如：测试[2023]1号");
                                }
                            }

                        }else  if(name.equals("bgqx")){
                            if(!value.equals("")){
                                String regex = "^(Y|D\\d{1,3})$";
                                Pattern pattern = Pattern.compile(regex);
                                Matcher matcher = pattern.matcher(value);

                                if (!matcher.matches()) {
                                    return R.error("如果是永久保存请输入\"Y\",如果是年份保存请输入\"D+保管年份");
                                }
                            }

                        }else  if(name.equals("unitno")){
                            if(!value.equals("")){
                                String regex = "^\\d{4}$";
                                Pattern pattern = Pattern.compile(regex);
                                Matcher matcher = pattern.matcher(value);

                                if (!matcher.matches()) {
                                    return R.error("件号必须为四位数字");
                                }
                            }

                        }else  if(name.equals("damldm")){
                            if(!value.equals("")){
                                String regex = "^[A-Z]{2}$";
                                Pattern pattern = Pattern.compile(regex);
                                Matcher matcher = pattern.matcher(value);

                                if (!matcher.matches()) {
                                    return R.error("档案门类代码应为2位大写字母组成");
                                }
                            }

                        }
                        if(StringUtils.equals(type,"int") || StringUtils.equals(type,"Integer")){
                            declaredField1.set(o,Integer.parseInt(value));
                        } else if(StringUtils.equals(type,"java.lang.String") || StringUtils.equals(type,"char") || StringUtils.equals(type,"Character") ||
                                StringUtils.equals(type,"byte") || StringUtils.equals(type,"Byte")){
                            declaredField1.set(o,value);
                        } else if(StringUtils.equals(type,"boolean") || StringUtils.equals(type,"Boolean")){
                            declaredField1.set(o,Boolean.valueOf(value));
                        } else if(StringUtils.equals(type,"double") || StringUtils.equals(type,"Double")){
                            declaredField1.set(o,Double.valueOf(value));
                        } else if (StringUtils.equals(type,"long") || StringUtils.equals(type,"Long")) {
                            declaredField1.set(o,Long.valueOf(value));
                        } else if(StringUtils.equals(type,"short") || StringUtils.equals(type,"Short")){
                            declaredField1.set(o,Short.valueOf(value));
                        } else if(StringUtils.equals(type,"float") || StringUtils.equals(type,"Float")){
                            declaredField1.set(o,Float.valueOf(value));
                        }else if(StringUtils.equals(type,"java.util.Date")){
                            declaredField1.set(o, strToDate2(value));
                        }
                    }
                }
                dataList.add(o);
            }
            workbook.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.ok().put("list",dataList);
    }

    /**
     * 标准字符串转Date
     * @param dateString
     * @return
     */

    public static Date strToDate(String dateString) {

        SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");

           Date date = null;
            try {
                date = format.parse(dateString);
            } catch (ParseException e) {
               e.printStackTrace();
            }
            System.out.println(date);
            return date;
        }
    /**
     * 格式化Date
     * @param date
     * @return
     */

    public static String dateToStr(Date date) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = format.format(date);
        System.out.println(dateString);
        return dateString;
    }
    /**
     * 普通字符串转Date
     * @param dateString
     * @return
     */
    public static Date strToDate2(String dateString) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        Date date = null;
        try {
            date = format.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(date);
        return date;
    }
    /**
     * 标准日期字符串转普通字符串
     * @param dateStr
     * @return
     */
    public static String bzstrToStr(String dateStr) {

        SimpleDateFormat inputFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate ="";
        try {
            Date date = inputFormat.parse(dateStr);
             formattedDate = outputFormat.format(date);
            System.out.println(formattedDate);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return formattedDate;
    }
}
